package com.heima.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1) 获取Request和Response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 2) 如果是/login放行
        if (request.getPath().toString().contains("/login")){
            return chain.filter(exchange);
        }

        // 2) 获取请求头中的令牌
        String token = request.getHeaders().getFirst("token");

        // 3) 解析令牌
        Map result = null;
        Object id = null;

        try {
            result = AppJwtUtil.getClaimsBody(token);

            // 4) 获取令牌中的userId
            id = result.get("id");
        } catch (Exception e) {
            // 如果无效，拦截
            //提示参数错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON); //响应JSON类型
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }
        String userId = String.valueOf(id);
        // 5) 传递userId
        exchange.mutate().request(builder -> builder.header("userId",userId));
        return chain.filter(exchange);
    }
}
